package com.bsoft.apiservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bsoft.apiservice.dto.DoSamplingRequest;
import com.bsoft.apiservice.dto.GetSampleRequest;
import com.bsoft.apiservice.dto.GetVisSampleListRequest;
import com.bsoft.apiservice.dto.SampleReceiveRequest;
import com.bsoft.apiservice.entity.*;
import com.bsoft.apiservice.mapper.GetSampleMapper;
import com.bsoft.apiservice.mapper.SampleReceiveMapper;
import com.bsoft.apiservice.mapper.VisSampleMapper;
import com.bsoft.apiservice.service.ApiService;
import lombok.Synchronized;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * @author Tangr
 * @version 1.0
 * @ClassName: ApiServiceImpl
 * @Description: TODO
 * @date 2023/12/13 10:34
 */
@Service
public class ApiServiceImpl implements ApiService {

    @Resource
    private VisSampleMapper visSampleMapper;

    @Resource
    private GetSampleMapper getSampleMapper;

    @Resource
    private SampleReceiveMapper sampleReceiveMapper;

    @Resource
    private JdbcTemplate jdbcTemplate;


    @Override
    public JSONObject getVisSampleList(GetVisSampleListRequest req) {
        JSONObject response = new JSONObject();
        response.put("code", "200");
        response.put("msg", "成功");
        List<InspectReport> list = visSampleMapper.getVisSampleList(req);
        response.put("data", list);
        return response;
    }

    @Override
    public JSONObject getVisSampleListX(GetVisSampleListRequest req) {
        JSONObject response = new JSONObject();
        response.put("code", "200");
        response.put("msg", "成功");
        List<InspectReport> list = visSampleMapper.getVisSampleListX(req);
        response.put("data", list);
        return response;
    }

    @Override
    @Synchronized
    @Transactional(rollbackFor = Exception.class)
    public JSONObject doSampling(DoSamplingRequest req) {
        JSONObject response = new JSONObject();
        String barCodeNo = req.getBarCodeNo();
        String opertionType = req.getOpertionType();
        barCodeNo = "202" + barCodeNo + "A";
//        doSamplingRequest.setBarCodeNo(barCodeNo);
        req.setBarCodeNo(barCodeNo);

        try {

            int count2 = visSampleMapper.updateJytmxx(req);
            response.put("code", "200");
            response.put("msg", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.put("code", "500");
            response.put("msg", e.getMessage());
        }
        return response;
    }

    @Override
    public JSONObject getSample(GetSampleRequest req) {
        JSONObject response = new JSONObject();
        response.put("code", "200");
        response.put("msg", "成功");
        List<InspectInfos> list = getSampleMapper.getSample(req);
        response.put("data", list);
        return response;
    }

    @Override
    public JSONObject sampleReceive(SampleReceiveRequest req) {
        JSONObject response = new JSONObject();
        SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String vbarcode = req.getVbarcode();
        String bhstatus = req.getBhstatus();
        String ksdm = req.getSection();
        Date samplingStartDate = req.getSamplingStartDate();
        Date samplingEndDate = req.getSamplingEndDate();
        String formatSamplingStartDate = sdf.format(samplingStartDate);
        String formatSamplingEndDate = sdf.format(samplingEndDate);

        String vbarcodeAll = "";
        String samplingUser = req.getSamplingUser();

        response.put("code", "200");
        response.put("msg", "成功！");
        if (vbarcode.length() < 10) {
            response.put("code", "-1");
            response.put("msg", "条码号错误！");
            return response;
        }


        List<SampleNumber> res = sampleReceiveMapper.sampleInfo(req);
        for (int i = 0; i < res.size(); i++) {
            SampleNumber sampleNumber = res.get(i);
            int li_find = sampleNumber.getLi_find();
            if (li_find < 1) {
                response.put("code", "-2");
                response.put("msg", "条码号过期或者条码号错误！");
                return response;
            }
        }
//        List<Integer> li_finds = res.stream().map(SampleNumber::getLi_find).collect(Collectors.toList());

        List<InspectInfos> list = sampleReceiveMapper.getDoctadviseno(req);

        for (int i = 0; i < list.size(); i++) {
            InspectInfos inspectInfos = list.get(i);
            vbarcodeAll = inspectInfos.getDoctadviseno();
        }
        if (vbarcodeAll.equals("") || vbarcodeAll == null) {
            response.put("code", "-2");
            response.put("msg", "条码号为空！");
            return response;
        }
        req.setVbarcode(vbarcodeAll);
        List<GetSample> sampleList = sampleReceiveMapper.getReceive(req);
        String stayhospitalmode = "";

        String sampleStatus = "";
        Date executetime = null;
        String executor = "";
        String section = "";
        for (int i = 0; i < sampleList.size(); i++) {
            GetSample getSample = sampleList.get(i);
            sampleStatus = getSample.getSampleStatus();
            section = getSample.getSection();
            stayhospitalmode = getSample.getStayhospitalmode();
            executetime = getSample.getExecutetime();
            executor = getSample.getExecutor();

        }

        if (sampleStatus == "0" || sampleStatus == "1" || sampleStatus == "4") {
            response.put("code", "-3");
            response.put("msg", "条码未在标本中心接受！");
            return response;
        }
        String sql = "";
        if (stayhospitalmode.equals("3") && !sampleStatus.equals("5")) {

//            sql = "insert into l_jytmxx_bbzq (xh,DOCTADVISENO,status,executor,executedate,signer,ksdm,sjks,sampleno,jgid,sjdh,ishgsj)" +
//                    "values ((select to_char(nvl(max(to_number(dzq)),0)+1) xh from gy_xhb where bm='l_jytmxx_bbzq'),'" + vbarcodeAll + "',10,'" + executor + "','" + executetime + "','检验科','接收中心','','分拣机',1,0,0)";
//


            req.setDoctadviseno(vbarcodeAll);
            String formatExecutetime = sdf.format(executetime);
            req.setExecutetime(formatExecutetime);
            req.setSamplingUser(executor);

            Integer insertSam = sampleReceiveMapper.saveBbzq(req);

            if (insertSam < 1) {
                response.put("code", "-3");
                response.put("msg", "更新失败！");
                return response;
            }

            sql = "update l_jytmxx set feestatus = 2,receiver = '检验科',receivetime = to_date("+formatExecutetime+",'yyyy-MM-DD HH24:MI:SS'),samplestatus = 5,sample_notes='标本合格' where jgid =83 and doctadviseno ='" + vbarcodeAll + "'";
            int updateSam = jdbcTemplate.update(sql);
            if (updateSam < 1) {
                response.put("code", "-3");
                response.put("msg", "更新失败！");
                return response;
            }
        }

        if (bhstatus.equals("1")  || bhstatus.equals("2")) {
            sql = "insert into T_HQ_SampleRecieve (doctadviseno,tmh,ksdm,zdbhstatus,zdbhkssj,zdbhjssj) values ('" + vbarcodeAll + "','" + vbarcode + "','" + ksdm + "','" + bhstatus + "',to_date('"+formatSamplingStartDate+"','yyyy-MM-DD HH24:MI:SS'),to_date('"+formatSamplingEndDate+"','yyyy-MM-DD HH24:MI:SS'))";
//            sql = "insert into l_testresult (sampleno,jgid,measuretime,testid,sampletype) values ('" + vbarcode +"','"  + bhstatus + "',to_date('"+formatSamplingStartDate+"','yyyy-MM-DD HH24:MI:SS'),'5031','C')";

            int insertSamRec = jdbcTemplate.update(sql);
            if (insertSamRec < 1) {
                response.put("code", "-3");
                response.put("msg", "更新失败！");
                return response;
            } else {
                response.put("code", "200");
                response.put("msg", "签收成功-自动编号！");
                return response;
            }
        } else {
            response.put("code", "200");
            response.put("msg", "签收成功-无自动编号！");
            return response;
        }
    }
}
